package com.jch.string_encoder;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DemoServerHandler extends ChannelInboundHandlerAdapter {

    // 连接建立时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        System.out.println(channel.remoteAddress().getHostString());
        System.out.println("连接报告Start");
        System.out.println("一个客户端接入");
        System.out.println("IP: " + channel.localAddress().getHostString());
        System.out.println("PORT: " + channel.localAddress().getPort());
        System.out.println("连接报告End");

        String msg = "连接成功 "  + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\r\n";
        ctx.writeAndFlush(msg);
    }

    // 客户端主动断开连接时触发
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端连接断开：" + ctx.channel().localAddress().toString());
    }

    // 读取客户端消息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String readDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println(readDate + " 收到消息：" + msg);
        String serverMsg = readDate + " 服务器收到消息：" + msg + "\r\n";
        ctx.writeAndFlush(serverMsg);
    }

    // 通信通道异常时触发
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.close();
        System.out.println("异常信息：" + cause.getMessage());
    }
}
